package com.heatingcharge.common.interceptor;

import com.heatingcharge.controller.pay.alipay.AbstractAliPayApiController;
import com.ijpay.alipay.AliPayApiConfigKit;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IntelliJ IDEA.
 * Description: heating_charge_server
 * User: Devin
 * Date: 2019-12-18
 * Time: 11:32
 */
public class AliPayInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        String allowHeaders = "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With, Authorization";
        response.addHeader("Access-Control-Allow-Headers", allowHeaders);
        response.setHeader("Access-Control-Allow-Methods", "POST, GET");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        if (HandlerMethod.class.equals(handler.getClass())){
            HandlerMethod method=(HandlerMethod)handler;
            Object controller = method.getBean();
            if (!(controller instanceof AbstractAliPayApiController)){
                throw new RuntimeException("控制器需要继承AliPayApiController");
            }
            AliPayApiConfigKit.setThreadLocalAliPayApiConfig(((AbstractAliPayApiController) controller).getApiConfig());
            return true;

        }
        return false;
    }
}
